﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using ST.Buz.Base.Entity;
using ST.Buz.Base.Enums;
using ST.Buz.Base.ViewModel;
using ST.Common.Data;
using ST.Common.Util;
using ST.Common.Util.Model;
using ST.Common.Util.Mvc;
using System;
using System.Collections.Generic;
using System.Data;
using Microsoft.Data.SqlClient;
using System.IO;
using System.Linq;

namespace ST.Buz.Service
{
	/// <summary>
	/// 只针对当前项目的扩展接口定义
	/// </summary>
	public partial interface IServiceSysUser
	{
		/// <summary>
		/// 获取当前用户详细信息
		/// </summary>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		VM_Sys_UserDetail GetDetailExt(UserSession sessionCurrent);

		/// <summary>
		/// 获取分页列表
		/// </summary>
		PageData GetDetailPageList(VMS_Sys_User searchModel);

		/// <summary>
		/// 更新用户信息
		/// </summary>
		/// <param name="oauthType"></param>
		/// <param name="appID"></param>
		/// <param name="sessionCurrent"></param>
		/// <param name="user"></param>
		/// <param name="oAuthDetail"></param>
		/// <returns></returns>
		UserSession Update(SessionType oauthType, string appID, UserSession sessionCurrent, Sys_User user, SysOAuthDetail oAuthDetail);

		/// <summary>
		/// 生成详细信息Excel
		/// </summary>
		byte[] GenerateExcel(List<VML_Sys_User> lst);
	}

	/// <summary>
	/// 只针对当前项目的扩展接口实现
	/// </summary>
	public partial class ServiceSysUser
	{
		/// <summary>
		/// 获取当前用户详细信息
		/// </summary>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		public VM_Sys_UserDetail GetDetailExt(UserSession sessionCurrent)
		{
			VM_Sys_UserDetail model = null;
			try
			{
				if (sessionCurrent == null || sessionCurrent.UserID == 0)
				{
					throw new ArgumentException("用户未登录");
				}
				model = (from u in context.SysUser
						 join o in context.SysOrganization on u.OrgID equals o.ID into uotmp
						 from uo in uotmp.DefaultIfEmpty()
							 //join a in context.SysArea on uo.AreaID equals a.ID into oatmp
							 //from oa in oatmp.DefaultIfEmpty()
						 where u.ID == sessionCurrent.UserID
						 select new VM_Sys_UserDetail()
						 {
							 UID = u.ID,
							 Avatar = u.AvatarUrl,
							 Name = u.Name,
							 OrgName = u.UserType > 0 ? uo.Name : "",
							 Mobile = u.Mobile,
						 }).SingleOrDefault();
				if (model == null)
				{
					throw new BuzException("未找到相关用户或用户未注册");
				}
				//model.Roles = serviceSysUserRole.GetRoleCodesArray(model.UID);
				if (sessionCurrent.PartnerID > 0)
				{
					model.Balance = (from p in context.Partner
									 where p.ID == sessionCurrent.PartnerID
									 select p.TotalCashBalance).SingleOrDefault();
				}
				model.Mobile = string.IsNullOrEmpty(model.Mobile) || model.Mobile.Length < 11 ? model.Mobile : (model.Mobile.Substring(0, 3) + "****" + model.Mobile.Substring(7, 4));
			}
			catch (ArgumentException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取对象信息出错");
				throw new BuzException("获取对象信息失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return model;
		}
		/// <summary>
		/// 分页列表
		/// </summary>
		public PageData GetDetailPageList(VMS_Sys_User searchModel)
		{
			return GetPageList(searchModel);
		}

		/// <summary>
		/// 用户自定义注册操作
		/// </summary>
		/// <param name="user"></param>
		/// <param name="oauth"></param>
		/// <param name="session"></param>
		private void OnRegister(Sys_User user, Sys_OAuth oauth, Sys_Session session)
		{
		}

		/// <summary>
		/// 用户自定义更新实体属性时是否修改
		/// </summary>
		/// <param name="propName"></param>
		/// <returns></returns>
		private bool OnColumnUpdate(string propName)
		{
			switch (propName)
			{
				default:
					return true;
			}
		}

		/// <summary>
		/// 用户删除时自定义其他操作
		/// </summary>
		/// <param name="id"></param>
		private void onDelete(int id)
		{
			//context.Database.ExecuteSqlRaw("DELETE FROM CM_BonusRank WHERE [UID]={0}", id);
		}

		/// <summary>
		/// 更新用户信息
		/// </summary>
		/// <param name="oauthType"></param>
		/// <param name="appID"></param>
		/// <param name="sessionCurrent"></param>
		/// <param name="user"></param>
		/// <param name="oAuthDetail"></param>
		/// <returns></returns>
		public UserSession Update(SessionType oauthType, string appID, UserSession sessionCurrent, Sys_User user, SysOAuthDetail oAuthDetail)
		{
			try
			{
				Sys_OAuth oauth = context.SysOAuth.SingleOrDefault(e => e.AppID == appID && e.OpenID == sessionCurrent.OpenID);
				if (oauth == null)
				{
					throw new BuzException("第三方登录信息不存在");
				}
				Sys_Dept dept = null;
				if (!string.IsNullOrEmpty(user.DeptName))
				{
					dept = context.SysDept.FirstOrDefault(m => m.OrgID == user.OrgID && m.Name == user.DeptName);
					if (dept == null)
					{
						dept = new Sys_Dept()
						{
							Name = user.DeptName,
							OrgID = user.OrgID
						};
						dept.Code = Guid.NewGuid().ToString("N");
						context.SysDept.Add(dept);
						context.SaveChanges();
					}
				}
				Sys_User userOld = context.SysUser.SingleOrDefault(e => e.ID == oauth.UserID);
				if (userOld == null)
				{
					throw new BuzException("第三方登录用户信息不存在");
				}
				userOld.Name = user.Name;
				userOld.Mobile = user.Mobile;
				userOld.OrgID = user.OrgID;
				userOld.DeptID = dept != null ? dept.ID : 0;
				context.SaveChanges();

				Sys_Session session = context.SysSession.SingleOrDefault(e => e.UserID == oauth.UserID && e.Type == (int)oauthType);
				if (session == null)
				{
					throw new BuzException("第三方登录用户会话信息不存在");
				}

				return GetUserSession(userOld, oauth, session, false);
			}
			catch (ArgumentException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "更新个人信息出错");
				throw new BuzException("更新个人信息失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}

		/// <summary>
		/// 生成详细信息Excel
		/// </summary>
		public byte[] GenerateExcel(List<VML_Sys_User> lst)
		{
			try
			{
				IWorkbook wb = new XSSFWorkbook();
				ISheet sheet = wb.CreateSheet();
				#region 定义一些样式，可以自定义
				//ICellStyle styleHeader = wb.CreateCellStyleWithBorder(HSSFColor.Grey25Percent.Index, HorizontalAlignment.Center, VerticalAlignment.Center);
				//ICellStyle MONEY_STYLE = GetCellStyleOfMoney(wb);
				//ICellStyle styleNumber = wb.CreateCellStyleOfNumber();
				//ICellStyle styleInteger = wb.CreateCellStyleOfInteger();
				//ICellStyle DEF_STYLE = GetCellStyle(wb);
				//DEF_STYLE.WrapText = true;//列自动换行
				//ICellStyle FOOTER_STYLE = GetCellStyle(wb, HSSFColor.LightCornflowerBlue.Index, HorizontalAlignment.Center, VerticalAlignment.Center);
				#endregion

				int rowIndex = 0;
				int cellIndex = 0;
				#region 写入数据
				#region 表头
				List<KeyValuePair<string, string>> lstColumn = new List<KeyValuePair<string, string>>()
					{
						new KeyValuePair<string, string>("姓名","Name"),
						new KeyValuePair<string, string>("昵称","NickName"),
						new KeyValuePair<string, string>("登录账号","Code"),
						new KeyValuePair<string, string>("性别","GenderText"),
						new KeyValuePair<string, string>("单位","OrgName"),
						new KeyValuePair<string, string>("部门","DeptName"),
						new KeyValuePair<string, string>("详细地址","DetailAddress"),
						new KeyValuePair<string, string>("联系电话","Mobile"),
						new KeyValuePair<string, string>("状态","StateText"),
						new KeyValuePair<string, string>("创建时间","AddDate"),
						new KeyValuePair<string, string>("创建人","AddManName"),
						new KeyValuePair<string, string>("上次登录时间","LastLoginDate"),
						new KeyValuePair<string, string>("上次登录IP","LastLoginIP"),
					};
				IRow rowHeader = sheet.CreateRow(rowIndex++);
				cellIndex = 0;
				foreach (var col in lstColumn)
				{
					rowHeader.CreateCell(cellIndex++).SetCellValue(col.Key);
				}
				#endregion
				if (lst != null)
				{
					//int cellIndexTJDW = NPOIExcelHelper.GetColumnNum("EA");
					foreach (var item in lst)
					{
						cellIndex = 0;
						IRow rowItem = sheet.CreateRow(rowIndex++);

						rowItem.CreateCell(cellIndex++).SetCellValue(item.Name);
						rowItem.CreateCell(cellIndex++).SetCellValue(item.NickName);
						rowItem.CreateCell(cellIndex++).SetCellValue(item.Code);
						rowItem.CreateCell(cellIndex++).SetCellValue(item.GenderText);
						rowItem.CreateCell(cellIndex++).SetCellValue(item.OrgName);
						rowItem.CreateCell(cellIndex++).SetCellValue(item.DeptName);
						rowItem.CreateCell(cellIndex++).SetCellValue(item.Province + item.City + item.District + item.Town + item.DetailAddress);
						rowItem.CreateCell(cellIndex++).SetCellValue(item.Mobile);
						rowItem.CreateCell(cellIndex++).SetCellValue(item.StateText);
						rowItem.CreateCell(cellIndex++).SetCellValue(item.AddDate.ToString("yyyy-MM-dd HH:mm:ss"));
						rowItem.CreateCell(cellIndex++).SetCellValue(item.AddManName);
						rowItem.CreateCell(cellIndex++).SetCellValue(item.LastLoginDate.HasValue ? item.LastLoginDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "");
						rowItem.CreateCell(cellIndex++).SetCellValue(item.LastLoginIP);
					}
				}
				#endregion
				using (MemoryStream ms = new MemoryStream())
				{
					wb.Write(ms);
					return ms.ToArray();
				}
			}
			catch (Exception ex)
			{
				throw new BuzException("导出失败，" + ex.Message);
			}
		}
	}
}